import {
  getUserVideoUrl,
  playVideo,
  pauseVideo,
  getTouristVideoUrl
} from "../../../api/course";

// pages/learn/video/video.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isLogin: getApp().globalData.isLogin,
    courseId: 0,
    hourId: 0,
    recordId: 0, // 记录 id
    baseUrl: 'https://1500001381.vod2.myqcloud.com/6c980af5vodcq1500001381/',
    url: '',
    progress: 0, // 播放进度
    duration: 0,
    watchDown: false,
    videoContext: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      courseId: Number(options.courseId),
      hourId: Number(options.hourId),
      isLogin: getApp().globalData.isLogin,
    })
  },

  /**
   * 加载视频链接
   */
  async loadVideoUrl() {
    let res;
    if (this.data.isLogin) {
      res = await getUserVideoUrl(this.data.hourId);
    } else {
      res = await getTouristVideoUrl(this.data.hourId);
    }

    this.setData({
      url: (this.data.baseUrl.includes('http') ? this.data.baseUrl : '') + res.videoUrl,
      duration: res.duration,
      progress: res.progresses,
    })

    if (this.data.isLogin && this.data.videoContext && this.data.duration !== this.data.progress) {
      this.data.videoContext.seek(this.data.progress);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.data.videoContext = wx.createVideoContext('healthVideo', this);

    this.loadVideoUrl();
  },

  /**
   * 开始/继续播放
   * @param {object} e 
   */
  async handlePlay(e) {
    if (this.data.isLogin) {
      let res = await playVideo(this.data.courseId, this.data.hourId);
      this.data.recordId = res.id;
    }
  },

  /**
   * 暂停播放
   * @param {object} e 
   */
  handlePause(e) {
    if (this.data.isLogin && this.data.recordId !== 0) {
      pauseVideo(this.data.recordId, this.data.progress);
    }
  },

  /**
   * 播放发生错误
   * @param {object} e 
   */
  handleError(e) {
    if (this.data.isLogin && this.data.recordId !== 0) {
      pauseVideo(this.data.recordId, this.data.progress);
    }
  },

  /**
   * 进度条更新
   * @param {object} e
   */
  handleTimeUpdate(e) {
    if (this.data.isLogin) {
      this.data.progress = parseInt(e.detail.currentTime);
      if (!this.data.watchDown && e.detail.duration - e.detail.progress < 60) {
        this.data.watchDown = true;
        pauseVideo(this.data.recordId, this.data.duration);
      }
    }
  },

  /**
   * 播放结束
   * @param {object} e
   */
  handleEnded(e) {
    if (this.data.isLogin && !this.data.watchDown && this.data.recordId !== 0) {
      pauseVideo(this.data.recordId, this.data.duration);
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.isLogin && this.data.recordId !== 0) {
      pauseVideo(this.data.recordId, this.data.progress);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})